// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
// 在页面中定义激励视频广告
let videoAd: UniNamespace.RewardedVideoAdContext | null = null;

export type RewardedVideoAdOp = {
  /** 广告加载完成回调 */
  adLoadCallback?: typeof adLoadCallback;
  /** 广告加载失败回调 */
  adErrorCallback?: typeof adErrorCallback;
  /** 广告关闭回调 */
  adCloseCallback: typeof adCloseCallback;
  /** 广告id */
  adUnitId?: string;
  /** 快手广告类型 */
  ksAdType?: number | undefined;
  /** 快手广告ID */
  ksAdUnitId?: number | undefined;
};

export class RewardedVideoAd {
  /** 广告id */
  public adUnitId: RewardedVideoAdOp['adUnitId'] = '';
  /** 快手广告类型 */
  public ksAdType: RewardedVideoAdOp['ksAdType'] = undefined;
  /** 快手广告ID */
  public ksAdUnitId: RewardedVideoAdOp['ksAdUnitId'] = undefined;
  public adLoadCallback: RewardedVideoAdOp['adLoadCallback'] = adLoadCallback;
  public adErrorCallback: RewardedVideoAdOp['adErrorCallback'] = adErrorCallback;
  public adCloseCallback: RewardedVideoAdOp['adCloseCallback'] = adCloseCallback;

  public constructor(op: RewardedVideoAdOp) {
    this.adUnitId = op.adUnitId;
    this.ksAdType = op.ksAdType;
    this.ksAdUnitId = op.ksAdUnitId;

    this.adCloseCallback = op.adCloseCallback || this.adCloseCallback;
    this.adErrorCallback = op.adErrorCallback || this.adErrorCallback;
    this.adLoadCallback = op.adLoadCallback || this.adLoadCallback;
    this.initAd();
  }
  /** 初始化广告 */
  public initAd() {
    this.destroy(); // 解决不销毁问题
    const that = this;
    setTimeout(() => {
      videoAd = null;
      videoAd = this.createRewardedVideoAd();
      videoAd?.offLoad(that.adLoadCallback!);
      videoAd?.onLoad(that.adLoadCallback!);
      videoAd?.offError(that.adErrorCallback!);
      videoAd?.onError(that.adErrorCallback!);
      videoAd?.offClose(that.adCloseCallback);
      videoAd?.onClose(that.adCloseCallback);
    }, 80);
  }

  /**
   * 得到广告实例
   */
  public getAdInstance() {
    !videoAd && this.createRewardedVideoAd();
    return videoAd;
  }

  /** 创建激励广告实例 */
  public createRewardedVideoAd() {
    const that = this;
    if (videoAd) {
      return videoAd;
    } else {
      let _videoAd: UniApp.RewardedVideoAdContext | null = null;
      // #ifdef MP-TOUTIAO || MP-WEIXIN
      _videoAd = uni.createRewardedVideoAd({
        adUnitId: that.adUnitId,
      });
      // #endif
      // #ifdef MP-KUAISHOU
      _videoAd = ks.createRewardedVideoAd({
        type: that.ksAdType!,
        unitId: that.ksAdUnitId!,
      });
      // #endif
      return _videoAd;
    }
  }
  /** 销毁 */
  public destroy() {
    try {
      videoAd?.destroy();
      videoAd = null;
    } catch (error) {
      videoAd = null;
    }
  }
}

/** 广告加载完成回调 */
function adLoadCallback() {
  console.log('激励视频创建成功====');
}

/** 广告加载失败回调 */
function adErrorCallback(err: unknown) {
  console.log('激励视频创建失败====', err);
}
/** 广告关闭回调 */
function adCloseCallback(res: { isEnded: boolean }) {
  console.log('关闭广告====', res);
}
